<template>
  <div v-loading="loading">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="dataForm"
    >
      <el-row>
        <el-col :span="12">
          <!-- prop="dealName" -->
          <el-form-item :label="$t('项目名称')">
            <!-- <el-input v-model="form.dealName" :placeholder="$t('项目名称')" show-word-limit maxlength="250" /> -->
            <template>
              <router-link
                target="_blank"
                :to="{
                  path: '/deal/home/dealBaseHome',
                  query: { id: form.dealId },
                }"
                class="link_a"
              >{{ form.dealName }}
              </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- prop="dealCharge" -->
          <el-form-item :label="$t('项目负责人')">
            <!-- <el-input v-model="form.dealCharge" :placeholder="$t('项目负责人')" /> -->
            <UserSelect
              v-model="form.dealCharge"
              disabled
              :placeholder="$t('项目负责人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('跟投总金额') + $t('金额单位')" prop="followCountMoney">
            <Money
              v-model="form.followCountMoney"
              :placeholder="$t('跟投总金额')"
              disabled
              unit="w"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配总金额') + $t('金额单位')" prop="allotCountMoney">
            <Money
              v-model="form.allotCountMoney"
              :placeholder="$t('分配总金额')"
              disabled
              unit="w"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配时间')" prop="allotDate">
            <el-date-picker
              v-model="form.allotDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('分配时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')">
            <el-input
              v-model="form.remark"
              :placeholder="$t('备注')"
              type="textarea"
              show-word-limit
              maxlength="1000"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="area-header">
            <span class="area-header-title">{{ $t("分配详情") }}</span>
          </div>
          <el-table
            :data="form.dealUserDistributionDetailsList"
            style="width: 100%"
            class="nowrapTable formTable"
            border
          >
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="跟投人" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("跟投人") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'dealUserDistributionDetailsList.' +
                      scope.$index +
                      '.followPerson'
                  "
                  :rules="dealUserDistributionDetailsListRules.followPerson"
                >
                  <UserSelect
                    v-model="scope.row.followPerson"
                    :placeholder="$t('跟投人')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('跟投金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("跟投金额")+$t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'dealUserDistributionDetailsList.' +
                      scope.$index +
                      '.followMoney'
                  "
                  :rules="dealUserDistributionDetailsListRules.followMoney"
                >
                  <Money
                    v-model="scope.row.followMoney"
                    :placeholder="$t('跟投总金额')"
                    unit="w"
                    @change="calcRatio(scope.row)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('跟投比例(%)')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("跟投比例(%)") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'dealUserDistributionDetailsList.' +
                      scope.$index +
                      '.followRatio'
                  "
                  :rules="dealUserDistributionDetailsListRules.followRatio"
                >
                  <Ratio
                    v-model="scope.row.followRatio"
                    :precision="4"
                    :controls="false"
                    :max="100"
                    disabled
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="税前个人分配金额" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("税前个人分配金额") +$t("金额单位") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'dealUserDistributionDetailsList.' +
                      scope.$index +
                      '.allotMoney'
                  "
                  :rules="dealUserDistributionDetailsListRules.allotMoney"
                >
                  <Money
                    v-model="scope.row.allotMoney"
                    :placeholder="$t('税前个人分配金额')"
                    unit="w"
                    @change="sumAllot()"
                  />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              v-if="!otherBtnHide"
              :label="$t('操作')"
              align="center"
              class-name="small-padding fixed-width"
              width="80"
            >
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="
                    delDealUserDistributionDetails(scope.$index, scope.row)
                  "
                >{{ $t("删除") }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addDealUserDistributionDetails"
            >{{ $t("添加") }}</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <FileTable
          :list.sync="form.fileList"
          data-type="deal_user_distribution"
          :menu-key="menuKey"
          has-permi="system:distribution"
          :btn-show="!otherBtnHide"
        />
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right">
      <!--保存 取消按钮-->
      <!-- <save-btn has-permi="system:distribution" /> -->
      <FormBtn
        ref="formBtn"
        :bus-data="form"
        has-permi="system:distribution"
        :menu-key="menuKey"
        :btn-hide="btnHide"
      />
    </div>
  </div>
</template>

<script>
import { saveDealUserDistribution, getDealUserDistribution, getDealInvest } from '@/api/deal/follow/distribution/dealUserDistribution'
import { delDealUserDistributionDetails } from '@/api/deal/follow/details/dealUserDistributionDetails'
import { ruoyiFloat } from '@/utils/ruoyi'

export default {
    data() {
        return {
            otherBtnHide: false,
            // 是否隐藏保存按钮
            btnHide: false,
           // 菜单标识
           menuKey: 'system:distribution',
            // 表单参数
            form: {
              dealUserDistributionDetailsList: [],
              fileList: []
            },
            dealId: this.$route.query.id,
            // 遮罩层
            loading: false,
            // 表单校验
            rules: {
                dealName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                dealCharge: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                followCountMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                allotCountMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                allotDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
            },
            dealUserDistributionDetailsListRules: {
              followPerson: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              followMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              followRatio: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              allotMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
            }
        }
    },
    watch: {
      'form.dealUserDistributionDetailsList': {
        handler() {
          this.form.followCountMoney = 0
          this.form.allotCountMoney = 0
          if (!this.isEmpty(this.form.dealUserDistributionDetailsList)) {
            this.form.dealUserDistributionDetailsList.forEach(item => {
              //  followMoney allotMoney
              if (item.followMoney) {
                this.form.followCountMoney += ruoyiFloat().formatNum(item.followMoney)
              }
              if (item.allotMoney) {
                this.form.allotCountMoney += ruoyiFloat().formatNum(item.allotMoney)
              }
            })
          }
        }
      }
    },
    created() {
       this.$bus.$emit('async_done')
    },
    methods: {
        // 初始化数据
        init(data) {
            this.loading = true
            if (data != null && data.id !== undefined) {
                getDealUserDistribution(data.id, this.dealId).then(response => {
                    this.form = response.data
                    this.loading = false
                }).catch(() => {
                  this.loading = false
                })
            } else {
                this.reset()
                 getDealUserDistribution('0', this.dealId).then(response => {
                    this.form.dealCharge = response.data.dealCharge
                    this.form.dealName = response.data.dealName
                })
                getDealInvest(this.dealId).then(res => {
                     const resData = res.data
                     let sumMoney = 0.0
                     resData.map(e => {
                      sumMoney += e.followMoney
                    })
                     this.form.followCountMoney = sumMoney
                     resData.map(e => {
                        const row = {
                          id: undefined,
                          followPerson: e.followPerson,
                          followMoney: e.followMoney,
                          followRatio: (e.followMoney / sumMoney * 100)
                        }
                        console.log(row)
                        this.form.dealUserDistributionDetailsList.push(row)
                    })
                      this.loading = false
                })
            }
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                dealId: this.$route.query.id,
                dealCharge: undefined,
                followCountMoney: undefined,
                allotCountMoney: undefined,
                allotDate: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                dealUserDistributionDetailsList: [],
                fileList: []
            }
            this.resetForm('form')
        },
        // 取消按钮
        cancel() {
            this.$parent.$parent.formOpen = false
            this.$parent.$parent.reset()
        },
        // 关闭form页面
        closeForm() {
            // 关闭form页面遮罩层
            this.loading = false
            // 关闭form页面
            if (this.$parent.$parent.formOpen !== undefined) {
              this.$parent.$parent.formOpen = false
            }
            // 刷新list页面
            if (this.$parent.$parent.getList !== undefined) {
              this.$parent.$parent.getList()
            }
        },
        /** 提交按钮 */
        submitForm(type) {
           return new Promise((resolve, reject) => {
               this.$refs['form'].validate(valid => {
                if (valid) {
                    this.loading = true
                    saveDealUserDistribution(this.form).then(response => {
                         if (response.code === 200) {
                            // 点击的按钮是保存并启动流程
                            if (type === 'process') {
                              // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                              this.form.id = response.data.id
                              // 启动流程
                              this.startProcess(response.data.id)
                              // 点击的仅保存
                            } else {
                              this.msgSuccess(this.$t('保存成功'))
                              // 关闭form页面
                              this.closeForm()
                            }
                            this.loading = false
                            resolve()
                          } else {
                            this.msgError(response.msg)
                            this.loading = false
                            reject()
                          }
                    }).catch(() => {
                    this.loading = false
                })
                } else {
                    this.locationError(document)
                }
            })
           })
        },
        addDealUserDistributionDetails() {
              const row = {
              id: undefined,
              followPerson: '',
              followMoney: '',
              followRatio: '',
              allotMoney: ''
            }
            if (!(this.form.dealUserDistributionDetailsList instanceof Array)) {
              this.$set(this.form, 'dealUserDistributionDetailsList', [])
            }
            this.$nextTick(() => {
              this.form.dealUserDistributionDetailsList.push(row)
            })
        },
        delDealUserDistributionDetails(index, row) {
          const id = row.id
          if (id !== undefined && id !== '' && id != null) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
          .then(() => {
            // 调用接口
            delDealUserDistributionDetails(id)
            this.form.dealUserDistributionDetailsList.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
              } else {
                this.form.dealUserDistributionDetailsList.splice(index, 1)
              }
        },
        calcRatio() {
            let sum = 0.0
            this.form.dealUserDistributionDetailsList.map(e => {
              if (e.followMoney) {
                sum += e.followMoney
              }
            })
              this.form.followCountMoney = sum
            // 计算百分比
            this.form.dealUserDistributionDetailsList.forEach(e => {
              if (e.followMoney && sum) {
                 e.followRatio = (e.followMoney / sum) * 100
              }
            })
        },
        sumAllot() {
          let sum = 0.0
            this.form.dealUserDistributionDetailsList.map(e => {
              if (e.allotMoney) {
                sum += e.allotMoney
              }
            })
              this.form.allotCountMoney = sum
        },
        // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      //  processData.title = this.form.actTitle;
      processData.title = '[' + this.form.dealName + ']分配记录'
      // 业务表名
      processData.dataTable = 'deal_user_distribution'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/deal/follow/investment/dealUserDistributionForm.vue'
      processData.viewPath = '@/views/deal/follow/investment/dealUserDistributionView.vue'
      // processData.viewPath = "@/views/anxin/bonus/anxinBonusApplicationView";
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    }
    }
}
</script>
